import { View, Image, Text } from '@tarojs/components'
import { useState, useEffect } from 'react'
import LgButton from '@/pages/components/button'
import Header from '@/pages/components/navCustomBar'
import Taro from '@tarojs/taro'
import Proxy from '@/network/proxy'
import { requestSystemUrl } from '@/network/baseUrl'
import { HttpGet, HttpPut } from '@/network/servers'
import Utils from '@/utils/index'
import { connect } from 'react-redux'
import { getBrowserController, getNet, getStorage, getWxSDKParams } from '@/pages/components/utils';
import '../../images/public/style.css'
import './index.scss'
const browserController = getBrowserController()
const net = getNet()
const storage = getStorage()
var wx = require('weixin-js-sdk')
const {
  getNowEnvironment,
  getNowToken,
  RemoveHTML,
  getQueryVariable,
  replaceHost
} = Utils


const requireContext = require.context("../../images/fileIcon", true, /^\.\/.*\.svg$/);
const svgs = requireContext.keys().map(requireContext);
const keys = requireContext.keys()
let fileObj = {}

keys.map((item, index) => {
  let str = item.replace('./', "").replace('.svg', "")
  fileObj[str] = svgs[index]
})


function App(props) {

  let {
    noticeAddr,
    userInfo,
    env,
    baseUrl,
    systemInfo1,
    isManage,
  } = props



  const getToken = () => {
    if (getQueryVariable('env') === 'weapp') {
      return getQueryVariable('lg_tk')
    } else {
      return storage.get('token') || getQueryVariable('lg_tk')
    }
  }


  const [detail, setDetail] = useState(null);
  const [fileList, setFileList] = useState([]);
  const [imgList, setImgList] = useState([]);
  const [newsId, setNewsId] = useState("");
  const [taskId, setTaskId] = useState('')

  const [isRead, setIsRead] = useState(0);
  const [type, setType] = useState('0');
  const [height, setHeight] = useState(0);
  const [systemInfo, setSystemInfo] = useState(systemInfo1)

  const getCommonData = () => {
    if (Utils.getQueryVariable('env') === 'weapp' || window.__wxjs_environment === 'miniprogram') {
      // 小程序端的h5
      if (!baseUrl) {

      } else {
        console.log('小程序');

        //应用内跳转
        let instance = Taro.getCurrentInstance()
        if (instance.router?.params) {
          let params = instance.router.params
          let id = params.newsId
          setNewsId(id)

          let url = "/api/news/info/detailed"
          HttpGet({
            url,
            data: {
              newsId: id,
            },
            load: true
          }).then(res => {
            if (res.code == 200 && res.data) {
              let attachments = res.data.newsAttachmentVoList
              if (attachments && attachments?.length !== 0) {
                let imgArr = [], fileArr = [];
                // console.log(attachments,'attachments11');

                attachments.map(item => {
                  // console.log(item,'item123');
                  item.url = item.attachmentUrl
                  item.name = item.attachmentName
                  let fileType = Utils.getFileType(item?.attachmentName)
                  if (fileType == 'img') {
                    imgArr.push(item)
                  } else {
                    fileArr.push(item)
                  }
                })
                // console.log(fileArr,'fileArr',imgArr);
                setFileList(fileArr)
                setImgList(imgArr)
              }
              // 2024-2-23适配详情页卡片小程序图片跨域开裂
              // 要展示的 HTML 字符串
              var htmlString = res.data.newsContent

              // 使用正则表达式匹配 img 标签的 src 属性并替换
              var modifiedHtml = htmlString.replace(/(<img[^>]+src=")([^"]+)("[^>]*>)/gi, function (match, p1, p2, p3) {
                // 根据条件修改 src 属性
                if (Utils.getQueryVariable('env') === 'weapp' && res.data.beEduPush == '1') {
                  return p1 + replaceHost(p2, systemInfo.governmentWebUrl) + p3;
                } else if (Utils.getQueryVariable('env') === 'weapp') {
                  return p1 + replaceHost(p2, baseUrl) + p3;
                } else {
                  return match; // 保持不变
                }
              });
              setTimeout(() => {
                res.data.newsContent = modifiedHtml
                setIsRead(res.data.readStatus)
                setDetail(res.data)
              }, 200);
            } else {
              Taro.showToast({
                title: res.msg,
                icon: 'none',
                duration: 2000
              })
            }
          })
        }
      }
    } else {
      console.log('App');

      // app内 1.应用内跳转(不需要获取通知地址和用户信息) 2.直接跳转
      let instance = Taro.getCurrentInstance()

      const browserController = getBrowserController()
      let height = browserController.getStatusBarHeight()
      setHeight(height)
      if (instance.router?.params) {
        let params = instance.router.params
        let id = params.newsId
        let taskReleaseId = params.taskReleaseId
        if (taskReleaseId == 'undefined') {
          taskReleaseId = ''
        }
        // console.log(params);

        setIsRead(isRead)
        setNewsId(id)
        setTaskId(taskReleaseId)
        console.log(newsId, 'newsId', getQueryVariable('lg_tk'), '123', params)
        console.log(storage.get('token') || getQueryVariable('lg_tk'))

        HttpGet({
          url: '/api/common/user',
          data: {
            token: getNowToken()
          },

        }).then((res1) => {
          HttpGet({
            url: '/api/common/system/server/info',
            data: {
              sysId: '264',
            },
          }).then((response) => {
            let url = response.data.webSvrAddr + "/api/news/info/detailed"
            HttpGet({
              url,
              data: {
                newsId: id,
              }
            }).then(res => {
              if (res.code == 200 && res.data) {
                let attachments = res.data.newsAttachmentVoList
                if (attachments && attachments?.length !== 0) {
                  let imgArr = [], fileArr = [];
                  // console.log(attachments,'attachments11');

                  attachments.map(item => {
                    if (res.data.beEduPush == '1') {
                      if (!(item.attachmentUrl.toLowerCase().includes('https://') || item.attachmentUrl.toLowerCase().includes('http://'))) {
                        item.attachmentUrl = systemInfo.governmentWebUrl + '/' + item.attachmentUrl
                      }
                    }
                    // console.log(item,'item123');
                    item.url = item.attachmentUrl
                    item.name = item.attachmentName
                    let fileType = Utils.getFileType(item?.attachmentName)
                    if (fileType == 'img') {
                      imgArr.push(item)
                    } else {
                      fileArr.push(item)
                    }
                  })
                  // console.log(fileArr,'fileArr',imgArr);
                  setFileList(fileArr)
                  setImgList(imgArr)
                }
                setIsRead(res.data.readStatus)
                setDetail(res.data)
              } else {
                Taro.showToast({
                  title: res.msg,
                  icon: 'none',
                  duration: 2000
                })
              }
            })
          })
        })
      }
    }
  }

  const download = async (item, index) => {
    let url = item.url
    if (window.__wxjs_environment === 'miniprogram' || Utils.getSystemInfo() === 'weapp') {
      Taro.showToast({
        title: '正在打开，请稍等！',
        icon: 'none',
        duration: 2000
      })


      const params = await getWxSDKParams([])
      wx.config(params);
      let fileUrl = replaceHost(url, baseUrl);
      if (detail.beEduPush == '1') {
        if (!(fileUrl.toLowerCase().includes('https://') || fileUrl.toLowerCase().includes('http://'))) {
          fileUrl = replaceHost(systemInfo.governmentWebUrl + '/' + fileUrl, systemInfo.governmentWebUrl)
        }
      }
      try {
        browserController.openFileForWebview(wx, { fileUrl, fileName: item.name })
      } catch (error) {
        Taro.showToast({ title: error, icon: 'none' })
      }
    } else {
      console.log('aaaaaaaaaaaaaaaaaaaaaaa11a', item);

      let arr = fileList.concat([])
      net.downloadFile({
        url,
        fileName: item.name,
        onProgress: process => {
          Taro.showToast({
            icon: 'loading',
            title: `正在下载${process}`
          })
        },
        onSuccess: path => {
          Taro.showToast({
            title: '下载成功',
            icon: 'success',
            duration: 2000

          })
          arr[index].preView = true
          storage.set(String(item.attachmentUrl), path)
          setFileList(arr)
        },
        onError: error => {
          Taro.showToast({
            title: '下载失败',
            icon: 'none',
            duration: 2000
          })
        }
      })
    }
  }

  const showPreView = (item) => {
    let arr = [], url = item.url
    if (Utils.getQueryVariable('env') === 'weapp' || window.__wxjs_environment === 'miniprogram') {
      if (detail.beEduPush == '1') {
        if (!item.url.toLowerCase().includes('https://')) {
          url = replaceHost(systemInfo.governmentWebUrl + '/' + item.url, systemInfo.governmentWebUrl)
          imgList.map(t => {
            arr.push(replaceHost(systemInfo.governmentWebUrl + '/' + t.url, systemInfo.governmentWebUrl))
          })
        }
      } else {
        url = replaceHost(url, baseUrl)
        imgList.map(t => {
          arr.push(replaceHost(t.url, baseUrl))
        })
      }
    } else {
      imgList.map(t => {
        arr.push(t.url)
      })
    }

    Taro.previewImage({
      current: url, // 当前显示图片的http链接
      urls: arr // 需要预览的图片http链接列表
    })
  }

  const goBack = () => {
    console.log(Utils.getQueryVariable('isManage'))
    if (Utils.getQueryVariable('isManage')) {
      Taro.redirectTo({
        url: `/pages/newsInfoApp/index?lg_tk=${storage.get('token')}&isManage=1`
      })
    } else {
      Taro.redirectTo({
        url: `/pages/newsInfoApp/index?lg_tk=${storage.get('token')}`
      })
    }
  }

  const showFile = (item) => {
    browserController.openFileReader(storage.get(item.attachmentUrl))
  }

  const initWxSdk = async () => {
    const params = getWxSDKParams(['previewImage', 'getLocation'])
    wx.config(params);
    wx.ready(function () {
      // config信息验证后会执行 ready 方法，所有接口调用都必须在 config 接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在 ready 函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在 ready 函数中。
      console.log('ready')
    });
    wx.error(function (res) {
      // config信息验证失败会执行 error 函数，如签名过期导致验证失败，具体错误信息可以打开 config 的debug模式查看，也可以在返回的 res 参数中查看，对于 SPA 可以在这里更新签名。
      console.log(res)
    });
  }

  useEffect(() => {
    document.title = '部门资讯详情'
    if (window.__wxjs_environment === 'miniprogram') {
      initWxSdk()
    }
    getCommonData()
    return () => {
      if (Utils.getSystemInfo() === 'weapp') {
        document.title = '部门资讯'
        window.getNoticeList && typeof window.getNoticeList === 'function' && window.getNoticeList()
      }
    }
  }, []);

  const callBack = (item) => {
    Taro.showModal({
      title: '提示',
      content: '确定要撤回该条资讯吗？',
      success: function (res) {
        if (res.confirm) {
          HttpPut({
            url: 'api/news/manage/callBack?newsId=' + item.newsId,
          }).then((result) => {
            if (result.code == 200) {
              Taro.showToast({
                title: '撤回成功',
                duration: 2000,
                mask: true
              })
              setTimeout(() => {
                Taro.redirectTo({
                  url: `/pages/newsInfoApp/index?lg_tk=${storage.get('token')}&isManage=1`
                })
              }, 300);
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  }
  return (
    <View className={"noticeDetail " + (detail && detail.userId == userInfo.userId ? 'my-noticeDetail' : '')} >
      {
        Utils.getQueryVariable('env') === 'weapp' || window.__wxjs_environment === 'miniprogram' ?
          "" :
          <Header
            className='header-top'
            mainTitle='部门资讯详情'
            mainTitleBlod={false}
            isTitlePositionLeft={true}
            needMainIcon={process.env.TARO_ENV === 'weapp' ? false : true}
            onClick={Taro.getCurrentInstance().router?.params.from ? goBack : ''}
          />
      }
      {
        detail ?
          <View className="header">
            <View className="title">{detail.newsTitle}</View>
            <View className="noticeInfo">
              <Text>{detail.userName}</Text>
              <Text style={{ margin: '0 10px', color: '#999999' }}>|</Text>
              <Text>{detail.releaseTime}</Text>
              <Text style={{ margin: '0 10px', color: '#999999' }}>|</Text>
              <Text>{detail.readCount}浏览</Text>
            </View>
          </View> : null
      }

      {
        detail ?
          (!getNowEnvironment() ? <View className="content" dangerouslySetInnerHTML={{ __html: detail.newsContent }}></View> :
            <View className="content">{RemoveHTML(detail.newsContent)}</View>
          ) : null
      }
      {
        <View className="attachment">
          <View className="imgBox">
            {
              imgList.map(item => {

                return (
                  <View className="imgItem" onClick={() => showPreView(item)}>
                    <Image className="imgSrc" src={(Utils.getQueryVariable('env') === 'weapp' || window.__wxjs_environment === 'miniprogram') && detail && detail.beEduPush == '1'
                      ? replaceHost(systemInfo.governmentWebUrl + item.url, systemInfo.governmentWebUrl) : Utils.getQueryVariable('env') === 'weapp' || window.__wxjs_environment === 'miniprogram'
                        ? replaceHost(item.url, baseUrl) : item.url} mode='aspectFill' />
                  </View>
                )
              })
            }
          </View>
          <View className="fileBox">
            {
              fileList.map((item, index) => {
                let icon = Utils.getFileType(decodeURIComponent(item.name))
                let fileIcon = {
                  "img": "0a00901",
                  "doc": "0a00101",
                  "ppt": "0a00201",
                  "pdf": "0a00501",
                  "txt": "0a00401",
                  "xls": "0a00301",
                  "music": "0a00601",
                  "video": "0a00701",
                  "html": "0a01001",
                  "zip": "0a01201",
                  "otr": "0a01101"
                }
                let src = fileObj[fileIcon[icon]]
                // console.log(`fileObj`, fileObj['0a00101'])
                // console.log(`src`, fileIcon[icon])
                let size = Utils.getFileSize(item.attachmentSize)
                return (
                  <View className="docItem">
                    <View className="docIcon">
                      <Image className="docImg" src={src} />
                    </View>
                    <View className="docInfo">
                      <View className="docName oneline">{decodeURIComponent(item.name)}</View>
                      <View className="docSize">{size}</View>
                    </View>
                    {
                      (storage.get(item.attachmentUrl) || item.preView) ?
                        <View className="preViewFile" onClick={() => showFile(item)}>
                          <Text>查看</Text>
                        </View>
                        :
                        Utils.getSystemInfo() === 'weapp' ?
                          <View className="preViewFile" onClick={() => download(item, index)}>
                            <Text>查看</Text>
                          </View>
                          :
                          <View
                            className="downLoadIcon_content"
                            onClick={() => download(item, index)}
                            style={Utils.getNowEnvironment() ? { width: '32px', height: '32px' } : ''}
                          >
                          </View>
                    }

                  </View>
                )
              })
            }
          </View>
        </View>
      }
      {
        detail && isManage === 1 ?
          <View className="index_footer">
            {/* <LgButton className="send_btn" onClick={() => callBack(detail)} color='close' type='B' width={678} height={88} >撤回</LgButton> */}
            <div className='recall' onClick={() => callBack(detail)}>撤回</div>
          </View>
          : ""
      }
    </View>
  )
}

const mainProps = ({ commonData }) => {
  return {
    userInfo: commonData.userInfo,
    env: commonData.env,
    noticeAddr: commonData.noticeAddr,
    baseUrl: commonData.baseUrl,
    systemInfo1: commonData.systemInfo,
    isManage: commonData.isManage,
  }
}

export default connect(mainProps)(App);
